<?php

if (!function_exists('removeComments')) {

    //Ham xoa comment trong cac file php, html, js, css.
    function removeComments($content, $ext) {
        $tokens = token_get_all($content);
        $out = "";
        $commentTokens = array(T_COMMENT);
        if (defined('T_DOC_COMMENT'))
            $commentTokens[] = T_DOC_COMMENT;
        if (defined('T_ML_COMMENT'))
            $commentTokens[] = T_ML_COMMENT;
        foreach ($tokens as $token) {
            if (is_array($token)) {
                if (in_array($token[0], $commentTokens)) {
                    continue;
                }
                $token = $token[1];
            }
            $out.=$token;
        }
        $out = preg_replace('/^<!--(.|\s)*?-->/', '', $out); //xoa <!-- -->
        if ($ext != 'php') {
            $out = preg_replace('/^\/\*(.|\s)*?\*\//', '', $out); //Xoa /* */ bat dau tu dau dong
            $out = preg_replace('/\s+\/\*(.|\s)*?\*\//', '', $out); //Xoa /* */ neu truoc co khoang trang
            $out = preg_replace('/^\/\/.*/', '', $out); //Xoa // dau dong
            $out = preg_replace('/(,|;|{|\(|\s)\/\/.*/', '\1', $out); //Xoa // voi dieu kien phia truoc phai co cac dau , ; { ( hoac khoang trang
        }
        $out = preg_replace('/[\r\n\t]+/', ' ', $out); //xoa tab xuong dong
        $out = preg_replace('/ \s+/', ' ', $out); // xoa cac khoang trang thua (in php manual)
        $out = preg_replace('/>\s+</', '><', $out); // xoa khoang cach giua cac the > < thanh ><
        //echo $out; exit;
        return trim($out);
    }
}